home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / DT_TRY.PY < prev    next >
Encoding:
Python Source  |  2000-06-29  |  11.0 KB  |  287 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64.  
  65. import string, sys, traceback
  66. from cStringIO import StringIO
  67. from DT_Util import ParseError, parse_params, render_blocks
  68. from DT_Util import namespace, InstanceDict
  69. from DT_Return import DTReturn
  70.  
  71. class Try:
  72.     """Zope DTML Exception handling
  73.     
  74.     usage:
  75.     
  76.     <!--#try-->
  77.     <!--#except SomeError AnotherError-->
  78.     <!--#except YetAnotherError-->
  79.     <!--#except-->
  80.     <!--#else-->
  81.     <!--#/try-->
  82.       
  83.     or:
  84.       
  85.     <!--#try-->
  86.     <!--#finally-->
  87.     <!--#/try-->
  88.     
  89.     The DTML try tag functions quite like Python's try command.
  90.     
  91.     The contents of the try tag are rendered. If an exception is raised,
  92.     then control switches to the except blocks. The first except block to
  93.     match the type of the error raised is rendered. If an except block has
  94.     no name then it matches all raised errors.
  95.     
  96.     The try tag understands class-based exceptions, as well as string-based
  97.     exceptions. Note: the 'raise' tag raises string-based exceptions.
  98.     
  99.     Inside the except blocks information about the error is available via
  100.     three variables.
  101.     
  102.       'error_type' -- This variable is the name of the exception caught.
  103.     
  104.       'error_value' -- This is the caught exception's value.
  105.     
  106.       'error_tb' -- This is a traceback for the caught exception.
  107.       
  108.     The optional else block is rendered when no exception occurs in the
  109.     try block. Exceptions in the else block are not handled by the preceding
  110.     except blocks.
  111.  
  112.     The try..finally form specifies a `cleanup` block, to be rendered even
  113.     when an exception occurs. Note that any rendered result is discarded if
  114.     an exception occurs in either the try or finally blocks. The finally block
  115.     is only of any use if you need to clean up something that will not be
  116.     cleaned up by the transaction abort code.
  117.  
  118.     The finally block will always be called, wether there was an exception in
  119.     the try block or not, or wether or not you used a return tag in the try
  120.     block. Note that any output of the finally block is discarded if you use a
  121.     return tag in the try block.
  122.  
  123.     If an exception occurs in the try block, and an exception occurs in the
  124.     finally block, or you use the return tag in that block, any information
  125.     about that first exception is lost. No information about the first
  126.     exception is available in the finally block. Also, if you use a return tag
  127.     in the try block, and an exception occurs in the finally block or you use
  128.     a return tag there as well, the result returned in the try block will be
  129.     lost.
  130.  
  131.     Original version by Jordan B. Baker.
  132.     
  133.     Try..finally and try..else implementation by Martijn Pieters.
  134.     """
  135.     
  136.     name = 'try'
  137.     blockContinuations = 'except', 'else', 'finally'
  138.     finallyBlock=None
  139.     elseBlock=None
  140.  
  141.     def __init__(self, blocks):
  142.         tname, args, section = blocks[0]
  143.  
  144.         self.args = parse_params(args)
  145.         self.section = section.blocks
  146.  
  147.  
  148.         # Find out if this is a try..finally type
  149.         if len(blocks) == 2 and blocks[1][0] == 'finally':
  150.             self.finallyBlock = blocks[1][2].blocks
  151.  
  152.         # This is a try [except]* [else] block.
  153.         else:
  154.             # store handlers as tuples (name,block)
  155.             self.handlers = []
  156.             defaultHandlerFound = 0
  157.  
  158.             for tname,nargs,nsection in blocks[1:]:
  159.                 if tname == 'else':
  160.                     if not self.elseBlock is None:
  161.                         raise ParseError, (
  162.                             'No more than one else block is allowed',
  163.                             self.name)
  164.                     self.elseBlock = nsection.blocks
  165.  
  166.                 elif tname == 'finally':
  167.                     raise ParseError, (
  168.                         'A try..finally combination cannot contain '
  169.                         'any other else, except or finally blocks',
  170.                         self.name)
  171.  
  172.                 else:
  173.                     if not self.elseBlock is None:
  174.                         raise ParseError, (
  175.                             'The else block should be the last block '
  176.                             'in a try tag', self.name)
  177.  
  178.                     for errname in string.split(nargs):
  179.                         self.handlers.append((errname,nsection.blocks))
  180.                     if string.strip(nargs)=='':
  181.                         if defaultHandlerFound:
  182.                             raise ParseError, (
  183.                                 'Only one default exception handler '
  184.                                 'is allowed', self.name)
  185.                         else:
  186.                             defaultHandlerFound = 1
  187.                             self.handlers.append(('',nsection.blocks))
  188.  
  189.     def render(self, md):
  190.         if (self.finallyBlock is None):
  191.             return self.render_try_except(md)
  192.         else:
  193.             return self.render_try_finally(md)
  194.  
  195.     def render_try_except(self, md):
  196.         result = ''
  197.  
  198.         # first we try to render the first block
  199.         try:
  200.             result = render_blocks(self.section, md)
  201.         except DTReturn:
  202.             raise
  203.         except:
  204.             # but an error occurs.. save the info.
  205.             t,v = sys.exc_info()[:2]
  206.             if type(t)==type(''):
  207.                 errname = t
  208.             else:
  209.                 errname = t.__name__
  210.  
  211.             handler = self.find_handler(t)
  212.                                     
  213.             if handler is None:
  214.                 # we didn't find a handler, so reraise the error
  215.                 raise
  216.  
  217.             # found the handler block, now render it
  218.             try:
  219.                 f=StringIO()
  220.                 traceback.print_exc(100,f)
  221.                 error_tb=f.getvalue()
  222.                 ns = namespace(md, error_type=errname, error_value=v,
  223.                     error_tb=error_tb)[0]
  224.                 md._push(InstanceDict(ns,md))
  225.                 return render_blocks(handler, md)
  226.             finally:
  227.                 md._pop(1)
  228.  
  229.         else:
  230.             # No errors have occured, render the optional else block
  231.             if (self.elseBlock is None):
  232.                 return result
  233.             else:
  234.                 return result + render_blocks(self.elseBlock, md)
  235.                
  236.     def render_try_finally(self, md):
  237.         result = ''
  238.         # first try to render the first block
  239.         try:
  240.             result = render_blocks(self.section, md)
  241.         # Then handle finally block
  242.         finally:
  243.             result = result + render_blocks(self.finallyBlock, md)
  244.         return result
  245.  
  246.     def find_handler(self,exception):
  247.         "recursively search for a handler for a given exception"
  248.         if type(exception)==type(''):
  249.             for e,h in self.handlers:
  250.                 if exception==e or e=='':
  251.                     return h
  252.             else:
  253.                 return None
  254.         for e,h in self.handlers:
  255.             if e==exception.__name__ or e=='' or self.match_base(exception,e):
  256.                 return h    
  257.         return None 
  258.  
  259.     def match_base(self,exception,name):
  260.         for base in exception.__bases__:
  261.             if base.__name__==name or self.match_base(base,name):
  262.                 return 1
  263.         return None
  264.         
  265.     __call__ = render
  266.